package com.meizi.drop.springboot.kubernetes.fabric.open;

import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.ExecListener;
import io.fabric8.kubernetes.client.dsl.ExecWatch;
import okhttp3.Response;

/**
 * @author meizi
 * @email enjoymeizi@gmail.com
 * @date 2021/1/13 22:53
 */
public class ExecExampleWithTerminalSize {
    public static void main(String[] args) throws InterruptedException {
        if (args.length < 1) {
            System.out.println("Usage: podName [namespace] [columns] [lines]\n" +
                    "Use env variable COLUMNS & LINES to initialize terminal size.");
            return;
        }

        String podName = args[0];
        String namespace = "default";
        String columns = "80";
        String lines = "24";

        if (args.length > 1) {
            namespace = args[1];
        }
        if (args.length > 2) {
            columns = args[2];
        }
        if (args.length > 3) {
            lines = args[3];
        }

        try (
                KubernetesClient client = new DefaultKubernetesClient();
                ExecWatch watch = newExecWatch(client, namespace, podName, columns, lines);
        ) {
            Thread.sleep(10 * 1000L);
        }
    }

    private static ExecWatch newExecWatch(KubernetesClient client, String namespace, String podName, String columns, String lines) {
        return client.pods().inNamespace(namespace).withName(podName)
                .readingInput(System.in)
                .writingOutput(System.out)
                .writingError(System.err)
                .withTTY()
                .usingListener(new SimpleListener())
                .exec("env", "TERM=xterm", "COLUMNS=" + columns, "LINES=" + lines, "sh", "-c", "ls -la");
    }

    private static class SimpleListener implements ExecListener {

        @Override
        public void onOpen(Response response) {
            System.out.println("The shell will remain open for 10 seconds.");
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            System.err.println("shell barfed");
        }

        @Override
        public void onClose(int code, String reason) {
            System.out.println("The shell will now close.");
        }
    }
}
